import { FC, useState } from "react";
import { produce } from "immer";
import QuestionCard from "../../components/QuestionCard";
import ListSearch from "../../components/ListSearch";
import { Empty } from "antd";

const list = [
  {
    _id: "q1",
    title: "问卷1",
    isPublished: true,
    isStar: true,
    answerCount: 3,
    createdAt: "3月11日 13:23",
  },
  {
    _id: "q2",
    title: "问卷2",
    isPublished: false,
    isStar: false,
    answerCount: 3,
    createdAt: "3月11日 13:23",
  },
  {
    _id: "q4",
    title: "问卷3",
    isPublished: true,
    isStar: true,
    answerCount: 3,
    createdAt: "3月11日 13:23",
  },
  {
    _id: "q5",
    title: "问卷4",
    isPublished: false,
    isStar: true,
    answerCount: 3,
    createdAt: "3月11日 13:23",
  },
];

const List1: FC = () => {
  const [questionList, setQuestionList] = useState(list);

  function addQuestion() {
    // const r = Math.random().toString().slice(-3);
    // setQuestionList(
    //   questionList.concat({
    //     id: "q" + r,
    //     title: "问卷" + r,
    //     isPublished: false,
    //   })
    // );
    // setQuestionList(
    //   produce(draft => {
    //     draft.push({
    //       id: "q" + r,
    //       title: "问卷" + r,
    //       isPublished: false,
    //     });
    //   })
    // );
  }

  function delQuestion(id: string) {
    setQuestionList(
      produce(draft => {
        const index = draft.findIndex(item => item._id === id);
        if (index > -1) {
          draft.splice(index, 1);
        }
      })
    );
  }

  function pubQuestion(id: string) {
    setQuestionList(
      produce(draft => {
        const item = draft.find(item => item._id === id);
        if (item) {
          item.isPublished = true;
        }
      })
    );
  }

  return (
    <div>
      <div className="flex justify-between mb-5">
        <div className="text-xl font-bold">我的问卷</div>
        <div>
          <ListSearch></ListSearch>
        </div>
      </div>
      <div>
        {questionList.length == 0 && <Empty />}
        {questionList.map(question => {
          const { _id } = question;
          return (
            <QuestionCard
              key={_id}
              {...question}
              delQuestion={delQuestion}
              pubQuestion={pubQuestion}
            ></QuestionCard>
          );
        })}
      </div>
      <div>
        <button onClick={addQuestion}>新增问卷</button>
      </div>
      <div>footer</div>
    </div>
  );
};

export default List1;
